package com.lyf.shop.dao.Impl;

import com.lyf.shop.dao.UserDao;
import com.lyf.shop.entity.User;
import com.lyf.shop.util.DataBaseUtil;
import com.lyf.shop.util.StrUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr = new QueryRunner();
    @Override
    public User findUserByUname(String username) throws SQLException {
        return qr.query(DataBaseUtil.getConnection(),
                "select * from user where uname=?",new BeanHandler<>(User.class),username);
    }

    @Override
    public int addUser(User user) throws SQLException {
        return qr.update(DataBaseUtil.getConnection(),
                "insert into user values (default ,?,?,?,?,?,?,?)",
                    user.getUname(),user.getUpassword(),user.getUemail(),
                user.getUsex(),user.getUstatus(),user.getUcode(),user.getUrole());
    }

    @Override
    public User getUserByEmailAndCode(String email, String code) throws SQLException{
        return qr.query(DataBaseUtil.getConnection(),"select * from user where uemail=? and ucode=?",new BeanHandler<>(User.class),email,code);
    }

    @Override
    public int updateUserStatus(int uid) throws SQLException{
        return qr.update(DataBaseUtil.getConnection(),"update user set ustatus=1 where  uid=?",uid);
    }

    @Override
    public List<User> userList() throws SQLException{
        return qr.query(DataBaseUtil.getConnection(),"select * from user",new BeanListHandler<>(User.class));
    }

    @Override
    public List<User> userList(String uname,String usex) throws SQLException{
        String sql = "select * from user where 1=1";
        List<Object> param = new ArrayList<>();
        if(StrUtils.empty(uname)){
            sql+=" and uname like ?";
            param.add("%"+uname+"%");
        }
        if(StrUtils.empty(usex)){
            sql+=" and usex = usex ";
            param.add(usex);
        }
        System.out.println(sql);
        System.out.println(param);
        return  qr.query(DataBaseUtil.getConnection(),sql,new BeanListHandler<>(User.class),param.toArray());
    }

    @Override
    public int deleteUser(int uid) throws SQLException{
        return qr.update(DataBaseUtil.getConnection(),"delete from user where uid=?",uid);
    }
}
